package com.zwxu.upload;

import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;


public class FtpUtil {
    private static String LOCAL_CHARSET = "GBK";
    // FTP协议里面，规定文件名编码为iso-8859-1
    private static String SERVER_CHARSET = "ISO-8859-1";

    public static void main(String[] args) throws IOException {
        FTPClient ftpClient = new FTPClient();

        ftpClient.connect("172.31.205.29", 21);

        ftpClient.login("aiftp", "Ftp2019@");
        if (FTPReply.isPositiveCompletion(ftpClient.sendCommand(
                "OPTS UTF8", "ON"))) {// 开启服务器对UTF-8的支持，如果服务器支持就用UTF-8编码，否则就使用本地编码（GBK）.
            LOCAL_CHARSET = "UTF-8";
        }
        ftpClient.setControlEncoding(LOCAL_CHARSET);
        ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
        ftpClient.enterLocalPassiveMode();

        File file = new File("/Users/zwxu/测试音频_16.wav");
        File distFile = new File("/Users/zwxu/ftp/测试音频_16.wav");

        String fileName = new String("/data/aiftp/0409/测试音频_16.wav".getBytes(LOCAL_CHARSET),SERVER_CHARSET);
        String destFileName = new String("/data/aiftp/0409/测试音频_16.wav".getBytes(LOCAL_CHARSET),SERVER_CHARSET);

        boolean flag = ftpClient.storeFile(fileName,new FileInputStream(file));
        System.out.println(flag + ":" + ftpClient.getReplyCode());
        FTPFile[] ftpFiles = ftpClient.listFiles("/data/aiftp/0409");
        for(FTPFile ftpFile:ftpFiles){
            System.out.println(ftpFile.getName());
        }


        boolean downloadFlag = ftpClient.retrieveFile(destFileName,new FileOutputStream(distFile));
        System.out.println(downloadFlag + ":" + ftpClient.getReplyCode());
        ftpClient.logout();
        ftpClient.disconnect();
    }
}